package com.anime.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.anime.adapter.YHSearchAnimeAdapter;
import com.anime.model.ViewModelSwitch;
import com.animes.R;
import com.anime.adapter.LRYSearchAnimeAdapter;
import com.animes.databinding.SearchAnimesActivityBinding;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import anime.room.HistoryModel;
import anime.room.HistoryViewModel;
import base.QActivity;
import base.QLoading;
import constant.AppConstants;
import http.Api;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import model.AnimeLRYSearchModel;
import model.AnimeYHSearchModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SearchAnimeActivity extends QActivity {

    private SearchAnimesActivityBinding binding;
    private LRYSearchAnimeAdapter lrySearchAnimeAdapter;
    private String searchName;
    private HistoryViewModel viewModel;
    private YHSearchAnimeAdapter yhSearchAnimeAdapter;
    private Disposable disposable;
    private int networkIndex = 0;
    private int pageNo = 1;
    private ViewModelSwitch viewSearchModel;
    private HashMap map = new HashMap<Integer, String>();
    private ArrayList<AnimeYHSearchModel.DataBean.ListBean> listData = new ArrayList<>();
    private int total;
    private QLoading dialog;

    @Override
    public int getLayoutRes() {
        return R.layout.search_animes_activity;
    }

    @Override
    public void initView() {
        binding = DataBindingUtil.setContentView(this, getLayoutRes());
    }

    @Override
    public void initData() {

        viewModel = new ViewModelProvider(this).get(HistoryViewModel.class);
        Bundle bundle = getIntent().getExtras();
        searchName = bundle.getString("searchName");


        binding.edSearch.setText(searchName);
        LinearLayoutManager lrylayoutManager = new LinearLayoutManager(this);
        lrylayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvLrysearch.setLayoutManager(lrylayoutManager);
        lrySearchAnimeAdapter = new LRYSearchAnimeAdapter(R.layout.search_anime_item, null);
        binding.rvLrysearch.setAdapter(lrySearchAnimeAdapter);


        LinearLayoutManager yhlayoutManager = new LinearLayoutManager(this);
        yhlayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvYhsearch.setLayoutManager(yhlayoutManager);
        yhSearchAnimeAdapter = new YHSearchAnimeAdapter(R.layout.search_anime_item, null);
        binding.rvYhsearch.setAdapter(yhSearchAnimeAdapter);

        viewSearchModel = new ViewModelProvider(this).get(ViewModelSwitch.class);


        // 设置刷新头部和尾部为经典样式
        binding.swipeContent.setRefreshHeader(new ClassicsHeader(this));
        binding.swipeContent.setRefreshFooter(new ClassicsFooter(this));
    }


    @Override
    public void initListener() {

        binding.swipeContent.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新
                LogUtils.d("下拉刷新A");


                if (pageNo * 20 < total) {
                    LogUtils.d("下拉刷新B");
                    pageNo = pageNo + 1;
                    getYHSearch(searchName);
                }

                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //上拉
                LogUtils.d("上拉刷新");
//
                getYHSearch(searchName);
                refreshLayout.finishRefresh();
            }
        });


        viewSearchModel.getSwitch().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer index) {

                int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, index);
                if (anInt == 1) {
                    binding.rvYhsearch.setVisibility(View.VISIBLE);
                    binding.rvLrysearch.setVisibility(View.GONE);
                    binding.ivSwitch.setImageResource(R.mipmap.switching);
                } else if (anInt == 2) {
                    binding.ivSwitch.setImageResource(R.mipmap.switching2);
                    binding.rvYhsearch.setVisibility(View.GONE);
                    binding.rvLrysearch.setVisibility(View.VISIBLE);
                }


            }
        });


        binding.ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
                if (anInt == 1) {
                    SPStaticUtils.put(AppConstants.SWITCHKEY, 2);
                    viewSearchModel.getSwitch().postValue(2);
                } else if (anInt == 2) {
                    SPStaticUtils.put(AppConstants.SWITCHKEY, 1);
                    viewSearchModel.getSwitch().postValue(1);
                }

            }
        });

        binding.edSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            pageNo = 1;
                            listData.clear();
                            getLRYSearchContext();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }

        });

        lrySearchAnimeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeLRYSearchModel.DataBean item = (AnimeLRYSearchModel.DataBean) adapter.getData().get(position);
                Intent intent = new Intent(SearchAnimeActivity.this, AnimePlayActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("videoId", item.getVideoId());
                intent.putExtra("pic",item.getCover());
                intent.putExtra("titleName",item.getTitle());
                startActivity(intent);

            }
        });

        yhSearchAnimeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeYHSearchModel.DataBean.ListBean item = (AnimeYHSearchModel.DataBean.ListBean) adapter.getData().get(position);
                Intent intent = new Intent(SearchAnimeActivity.this, AnimePlayActivity.class);
                intent.putExtra("yhid", item.getId());
                intent.putExtra("type", 2);
                intent.putExtra("titleName",item.getName());
                intent.putExtra("pic",item.getPic());
                startActivity(intent);
            }
        });
        binding.edSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                listData.clear();
                searchName = binding.edSearch.getText().toString().trim();
                getTypeSearch(searchName);

            }
        });

        binding.ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                listData.clear();
                getLRYSearchContext();
            }
        });


    }


    public void getLRYSearchContext() {
        dialog = new QLoading();
        dialog.showNow(getSupportFragmentManager(),"");
        searchName = binding.edSearch.getText().toString().trim();
        if (com.alibaba.android.arouter.utils.TextUtils.isEmpty(searchName)) {
            ToastUtils.showLong("请输入搜索内容");
            return;
        }

        int searchId = SPStaticUtils.getInt("AnimesearchId", 0);
        int newsearchId = searchId + 1;
        LogUtils.d("保存的Id" + newsearchId);
        SPStaticUtils.put("AnimesearchId", newsearchId);
        viewModel.addHistoryDao(new HistoryModel(newsearchId, searchName));
        viewModel.getAllSLive().getValue();

        getTypeSearch(searchName);


    }


    public void getTypeSearch(String searchName) {
        listData.clear();
        int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
        if (anInt == 1) {
            getYHSearch(searchName);
            binding.rvYhsearch.setVisibility(View.VISIBLE);
            binding.rvLrysearch.setVisibility(View.GONE);
            binding.swipeContent.setVisibility(View.VISIBLE);
        } else if (anInt == 2) {
            getLRYSearch(searchName);
            binding.rvYhsearch.setVisibility(View.GONE);
            binding.rvLrysearch.setVisibility(View.VISIBLE);
            binding.swipeContent.setVisibility(View.GONE);
        }

    }

    @Override
    public void networkMessage() {
             dialog = new QLoading();
        dialog.showNow(getSupportFragmentManager(),"");

        getTypeSearch(searchName);


    }

    private void getLRYSearch(String search) {
        if(TextUtils.isEmpty(search)){
            ToastUtils.showLong("搜索内容为空，请输入正确内容");
            return;
        }
        Call<AnimeLRYSearchModel> call = Api.getInstance().service.getLRYSearch("title", search, 1, 100);
        call.enqueue(new Callback<AnimeLRYSearchModel>() {
            @Override
            public void onResponse(Call<AnimeLRYSearchModel> call, Response<AnimeLRYSearchModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {
                    lrySearchAnimeAdapter.replaceData(response.body().getData());
                } else {
                    lrySearchAnimeAdapter.replaceData(new ArrayList<>());
                    if(response.body()!=null && response.body().getMsg()!=null){
                        ToastUtils.showLong(response.body().getMsg() + "状态码:" + response.code());
                    }
                }
                dialog.dismiss();

            }

            @Override
            public void onFailure(Call<AnimeLRYSearchModel> call, Throwable t) {
                LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());
            }
        });
    }


    private void getYHSearch(String search) {
        if(TextUtils.isEmpty(search)){
            ToastUtils.showLong("搜索内容为空，请输入正确内容");
            return;
        }
        map.clear();
        map.put("page", pageNo);
        map.put("keywords", search);
        Call<AnimeYHSearchModel> call = Api.getInstance().service.getYHSearch(map);
        call.enqueue(new Callback<AnimeYHSearchModel>() {
            @Override
            public void onResponse(Call<AnimeYHSearchModel> call, Response<AnimeYHSearchModel> response) {
                LogUtils.d("getYHSearch网络请求数据" + call.toString(), response.body() + "--->" + networkIndex);

                if (response.body() != null && response.body().getData() != null && response.body().getData().getList() != null) {
                    List<AnimeYHSearchModel.DataBean.ListBean> data = response.body().getData().getList();
                    if (response.body().getData().getList().size() == 0) {
                        ToastUtils.showLong("暂无数据，或搜索名字不正确,或切换搜索模式试下");
                    }
                    total = response.body().getData().getTotal();
                    dialog.dismiss();
                    yhSearchAnimeAdapter.replaceData(response.body().getData().getList());


                    if (pageNo == 1) {
                        binding.rvYhsearch.scrollToPosition(0);
                        yhSearchAnimeAdapter.replaceData(response.body().getData().getList());
                    } else {
                        if (response.body().getData().getList().size() == 0) {
                            binding.swipeContent.finishLoadMoreWithNoMoreData();
                        } else {

                        }
                    }
                    for (int i = 0; i < data.size(); i++) {
                        listData.add(data.get(i));
                    }
                    ;
                    yhSearchAnimeAdapter.replaceData(listData);


                } else {

                    if (networkIndex <= 3) {
                        setTime(search);
                        networkIndex++;
                    } else {
                        ToastUtils.showLong("没有数据，请切换模式试下");
                    }

                }


            }

            @Override
            public void onFailure(Call<AnimeYHSearchModel> call, Throwable t) {

                LogUtils.d("网络请求失败:" + t.getMessage());

                if (networkIndex <= 3) {
                    setTime(search);
                    networkIndex++;
                } else {
                    LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                    ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());
                }
            }
        });
    }

    public void setTime(String search) {
        stopDisposable(disposable);
        disposable = Flowable.timer(1 * 1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        getYHSearch(search);
                    }
                });
    }


    /**
     * 关闭定时器
     *
     * @param disposable 定时器
     */
    private void stopDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
        if (anInt == 1) {
            viewSearchModel.getSwitch().postValue(1);
        } else if (anInt == 2) {
            viewSearchModel.getSwitch().postValue(2);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopDisposable(disposable);
    }
}
